package com.zm.taobao;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.print.attribute.ResolutionSyntax;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.util.logging.resources.logging;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.PropKit;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.FileItem;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.ItemSellerGetRequest;
import com.taobao.api.request.ItemUpdateRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.PictureGetRequest;
import com.taobao.api.request.PictureUploadRequest;
import com.taobao.api.request.TopAuthTokenRefreshRequest;
import com.taobao.api.request.TraderatesGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.request.UserSellerGetRequest;
import com.taobao.api.response.ItemSellerGetResponse;
import com.taobao.api.response.ItemUpdateResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.PictureGetResponse;
import com.taobao.api.response.PictureUploadResponse;
import com.taobao.api.response.TopAuthTokenRefreshResponse;
import com.taobao.api.response.TraderatesGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
import com.taobao.api.response.UserSellerGetResponse;
import com.zm.core.controller.FrontController;
import com.zm.core.model.Product;
import com.zm.core.model.User;

/**
 * @author 贾尧尧
 *
 */
public class API {

	protected static String url = "";
	protected static String appkey = "";
	protected static String secret = "";

	static {
		String is = PropKit.use("shoesize.properties").get("username");
		if (is.equals("root")) {// 沙箱
			url = "http://gw.api.tbsandbox.com/router/rest";// 沙箱获取token
			appkey = "1023273354";
			secret = "sandbox3a41b14f86eb61d4fd7dec7dc";
		} else {// 正式
			url = "http://gw.api.taobao.com/router/rest";
			appkey = "23273354";
			secret = "82326063a41b14f86eb61d4fd7dec7dc";
		}
	}

	/**
	 * /**
	 * 
	 * @return taobao.user.seller.get (查询卖家用户信息)
	 *         {"user_seller_get_response":{"user"
	 *         :{"nick":"j11016","user_id":366426558
	 *         },"request_id":"11ifit8dw14fd"}}
	 */
	public static User getCurrentUser() {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UserSellerGetRequest req = new UserSellerGetRequest();
		req.setFields("user_id,nick");
		UserSellerGetResponse response = null;
		try {
			response = client.execute(req, Token.get());
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogFactory.getLog(API.class)
					.error("getCurrentUser错误message" + e.getMessage());
		}

		JSONObject job = JSONObject.fromObject(response.getBody());
		JSONObject items = job.getJSONObject("user_seller_get_response");
		JSONObject item = items.getJSONObject("user");
		User user = new User();
		System.out.println(item.getString("nick") + "==" + item.get("nick").toString());
		user.setNick(item.get("nick").toString());
		user.setUser_id(item.get("user_id").toString());

		return user;
	}

	/**
	 * @param title
	 *            taobao.items.onsale.get (获取当前会话用户出售中的商品列表)
	 */
	public static List<Product> getOnSaleProduct(String title) {
		List<Product> list = new ArrayList<Product>();
		List<Product> list1 = null;
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("num_iid,title,price,approve_status");
		if (title != null && !title.equals("")) {
			req.setQ(title);
		}
		int a = 1;
		while (true) {
			try {

				req.setPageNo(Long.parseLong(a + ""));
				req.setOrderBy("sold_quantity:desc");
				req.setPageSize(200L);
				ItemsOnsaleGetResponse response = null;
				try {
					response = client.execute(req, Token.get());
				} catch (ApiException e) {
					e.printStackTrace();
					LogFactory.getLog(API.class)
							.error("getOnSaleProduct错误message" + e.getMessage());
				}
				JSONObject job = JSONObject.fromObject(response.getBody());
				JSONObject items = job.getJSONObject("items_onsale_get_response");
				if (items != null && items.getInt("total_results") > 0) {
					JSONObject item = items.getJSONObject("items");
					if (item != null && item.size() > 0) {
						String array = item.getString("item");
						Gson gson = new Gson();
						list1 = gson.fromJson(array, new TypeToken<List<Product>>() {
						}.getType());
						list.addAll(list1);
					}

				} else {
					break;
				}
				a += 1;
			} catch (Exception e) {
				e.printStackTrace();
				LogFactory.getLog(API.class).error("getOnSaleProduct错误message" + e.getMessage());
				return list;
			}
		}

		return list;

	}

	/**
	 * @param title
	 * @return taobao.items.inventory.get (得到当前会话用户库存中的商品列表)
	 */
	public static List<Product> getInStockProduct(String title) {
		List<Product> list = null;
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemsInventoryGetRequest req = new ItemsInventoryGetRequest();
		req.setFields("num_iid,title,price,approve_status");
		if (title != null && !title.equals("")) {
			req.setQ(title);
		}
		req.setPageNo(1L);
		req.setPageSize(500L);
		ItemsInventoryGetResponse response = null;
		try {
			response = client.execute(req, Token.get());
		} catch (ApiException e) {
			e.printStackTrace();
			LogFactory.getLog(API.class)
					.error("getInStockProduct错误message" + e.getMessage());
		}
		JSONObject job = JSONObject.fromObject(response.getBody());
		JSONObject items = job.getJSONObject("items_inventory_get_response");
		if (items != null && items.getInt("total_results") > 0) {
			JSONObject item = items.getJSONObject("items");
			if (item != null) {
				String array = item.getString("item");
				Gson gson = new Gson();
				list = gson.fromJson(array, new TypeToken<List<Product>>() {
				}.getType());
			}

		}
		return list;
	}

	/**
	 * @return taobao.trades.sold.get (查询卖家已卖出的交易数据（根据创建时间）)
	 */
	public static String getSelledProduct() {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		req.setFields("total_results,tid,type,status");
		req.setStartCreated(StringUtils.parseDateTime("2000-01-01 00:00:00"));
		req.setEndCreated(StringUtils.parseDateTime("2000-01-01 23:59:59"));
		req.setType("fixed,auction,guarantee_trade,auto_delivery,independent_simple_trade,independent_shop_trade,cod,fenxiao,nopaid");
		TradesSoldGetResponse rsp = null;
		try {
			rsp = client.execute(req, Token.get());
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogFactory.getLog(API.class)
					.error("getSelledProduct错误message" + e.getMessage());
		}
		return rsp.getBody();
	}

	/**
	 * 根据num_iid获取商品详情
	 * 
	 * @author 李彤彤 2015年10月18日下午8:57:51
	 */
	public static String getProductDetail(String num_iid) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemSellerGetRequest req = new ItemSellerGetRequest();
		req.setFields("desc");
		req.setNumIid(Long.parseLong(num_iid));
		ItemSellerGetResponse response = null;
		try {
			response = client.execute(req, Token.get());
			JSONObject job = JSONObject.fromObject(response.getBody());
			JSONObject pics = job.getJSONObject("item_seller_get_response");
			JSONObject pic = pics.getJSONObject("item");
			String picarr = pic.getString("desc");
			return picarr;
		} catch (Exception e) {
			e.printStackTrace();
			LogFactory.getLog(API.class).error("getProductDetail错误message" + e.getMessage());
			return "error";
		}
	}

	/**
	 * 根据numid获取评价信息
	 * 
	 * @author 李彤彤 2015年10月21日下午7:43:32
	 */
	public static String getEvaluateByNumId(String numId) {
		// 示例numid:44730736425
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TraderatesGetRequest req = new TraderatesGetRequest();
		req.setFields("tid,oid,role,rated_nick,nick,result,created,item_title,item_price,content,reply");
		req.setRateType("get");
		req.setRole("buyer");
		req.setNumIid(Long.parseLong(numId));
		TraderatesGetResponse response = null;
		try {
			response = client.execute(req, Token.get());
		} catch (ApiException e) {
			LogFactory.getLog(API.class)
					.error("getEvaluateByNumId错误message" + e.getMessage());
			e.printStackTrace();
		}
		return response.getBody();
	}

	/**
	 * 更新商品的宝贝描述
	 * 
	 * @author 李彤彤 2015年10月21日下午7:56:33
	 */
	public static String updateProductDesc(String numId, String desc) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemUpdateRequest req = new ItemUpdateRequest();
		req.setNumIid(Long.parseLong(numId));
		req.setDesc(desc);
		ItemUpdateResponse rsp = null;
		try {
			rsp = client.execute(req, Token.get());
		} catch (ApiException e) {
			e.printStackTrace();
			LogFactory.getLog(API.class)
					.error("updateProductDesc错误message" + e.getMessage());
			return "error";
		}
		return rsp.getBody();
	}

	/**
	 * 将图片上传到淘宝工作空间
	 * 
	 * @param url
	 * @param title
	 * @return
	 */
	public static String uploadPicToTaobao(FileItem fileitem, String title) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		PictureUploadRequest req = new PictureUploadRequest();
		req.setPictureCategoryId(Long.parseLong("0"));
		req.setImg(fileitem);
		req.setImageInputTitle(title);
		req.setTitle(title.substring(0, title.indexOf(".")));
		req.setIsHttps(true);
		PictureUploadResponse rsp = null;

		try {
			rsp = client.execute(req, Token.get());
		} catch (ApiException e) {
			e.printStackTrace();
			LogFactory.getLog(API.class).error("uploadPicToTaobao错误message" + e.getMessage());
			return "error";
		}
		return rsp.getBody();
	}

	public static String getPicFormTaobao(String title) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		PictureGetRequest req = new PictureGetRequest();
		req.setTitle(title);
		PictureGetResponse response = null;
		try {
			response = client.execute(req, Token.get());

			JSONObject job = JSONObject.fromObject(response.getBody());
			JSONObject pics = job.getJSONObject("picture_get_response");
			JSONObject pic = pics.getJSONObject("pictures");
			JSONArray picarr = pic.getJSONArray("picture");
			String picurl = ((JSONObject) picarr.get(0)).getString("picture_path");
			return picurl;
		} catch (Exception e) {
			e.printStackTrace();
			Token.refresh();
			LogFactory.getLog(API.class).error("getPicFormTaobao错误message" + e.getMessage()+"token="+ Token.get());
			return "error";
		}
	}
	
	public static String refreshToken(){
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TopAuthTokenRefreshRequest req = new TopAuthTokenRefreshRequest();
		req.setRefreshToken(Token.refresh_token);
		TopAuthTokenRefreshResponse rsp;
		try {
			rsp = client.execute(req);
			System.out.println(rsp.getBody());
			JSONObject job = JSONObject.fromObject(rsp.getBody());
			JSONObject pics = job.getJSONObject("top_auth_token_refresh_response");
			JSONObject pic = pics.getJSONObject("token_result");
			String re_token = pic.getString("refresh_token");
			String ac_token = pic.getString("access_token");
			Token.refresh_token=re_token;
			Token.token=ac_token;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return appkey;
	}
}
